let express = require("express");
let router = express.Router();
let db = require("../db/index");

// 发布文章接口
router.post('/add', function (req, res, next) {
  let {title, detail, society_id, creationTime} = req.body;
  db.query(`INSERT INTO article set ?`, {title, detail, society_id, creationTime}, function (err) {
    if (!err) {
      res.send({
        code: 200,
        message: '发布文章成功'
      })
    } else {
      res.send({
        code: 20001,
        message: err.message
      })
    }
  })
})

router.post('/update',function (req,res){
  let {detail,id} = req.body;
  console.log(req.body)
  db.query(`UPDATE article SET detail = ? WHERE id = ?`,[detail,id],function (err) {
    if (err){
      res.send({
        code:20006,
        message:'更新失败'
      })
    }else {
      res.send({
        code:200,
        message:'成功'
      })
    }
  })
})

router.get('/info', function (req, res) {
  let {society_id,pageNo,limit} = req.query;
  let start = (pageNo-1)*limit
  db.query(`SELECT * FROM article WHERE society_id = '${society_id}' ORDER BY id DESC LIMIT ${start},${limit}`, function (err, rows) {
    if (!err) {
      db.query(`SELECT count(id) AS total FROM article WHERE society_id = '${society_id}'`,function (err2,rows2) {
        res.send({
          code: 200,
          message: 'success',
          data: {
            articleList: rows,
            total:rows2[0].total
          }
        })
      })
    } else {
      res.send({
        code: 20002,
        message: err.message
      })
    }
  })
})

router.post('/del', function (req, res) {
  let {ids} = req.body;
  db.query(`DELETE FROM article WHERE id in (${ids})`, function (err) {
    if (err) {
      res.send({
        code: 20003,
        message: err.message
      })
    } else {
      res.send({
        code: 200,
        message: '成功'
      })
    }
  })
})
module.exports = router;